"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

(function (root, factory) {
  factory.bind(root);

  if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object' && (typeof module === "undefined" ? "undefined" : _typeof(module)) === 'object') {
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    define("wtools", [], factory);
  } else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
    exports["wtools"] = factory();
  } else {
    root["wtools"] = factory();
  }
})(typeof window !== "undefined" ? window : void 0, function () {
  "use strict";

  var VERSION = "1.5.0"; // app存储

  var APP_STORAGE = "app"; // session存储

  var SESSION_STORAGE = "session"; // local存储

  var LOCAL_STORAGE = "local"; // 默认语言

  var ZH_CN = "zh_cn"; // 模板标识符

  var OBJTYPE = "DOMMAP"; // ajax请求方式

  var AJAX_REQUEST_GET = "GET";
  var AJAX_REQUEST_POST = "POST";
  var AJAX_REQUEST_JSONP = "JSONP"; // ajax参数格式

  var AJAX_PARAMS_MATHOD_JSON = "json";
  var AJAX_PARAMS_MATHOD_FORMDATA = "form_data";
  var AJAX_PARAMS_MATHOD_STRINGIFY = "stringify";

  var installer = function () {
    var constructor = {};
    Object.defineProperty(constructor, "version", {
      value: VERSION,
      enumerable: true,
      writeable: false
    });

    var installer = function construct() {
      this.version = VERSION;
    };

    installer.prototype.install = function (name) {
      var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      if (!constructor[name]) {
        Object.defineProperty(constructor, name, {
          value: {},
          enumerable: true,
          writeable: false
        });
      }

      for (var key in target) {
        Object.defineProperty(constructor[name], key, {
          value: target[key],
          enumerable: true,
          writeable: false
        });
      }

      return true;
    };

    installer.prototype.append = function (name, target) {
      Object.defineProperty(constructor, name, {
        value: target,
        enumerable: true,
        writeable: false
      });
    };

    installer.prototype.get = function () {
      return constructor;
    };

    return new installer();
  }();

  var trace = function trace() {};

  var polyfill = function polyfill() {
    if (typeof Object.assign != 'function') {
      // Must be writable: true, enumerable: false, configurable: true
      Object.defineProperty(Object, "assign", {
        value: function assign(target, varArgs) {
          // .length of function is 2
          'use strict';

          if (target == null) {
            // TypeError if undefined or null
            throw new TypeError('Cannot convert undefined or null to object');
          }

          var to = Object(target);

          for (var index = 1; index < arguments.length; index++) {
            var nextSource = arguments[index];

            if (nextSource != null) {
              // Skip over if undefined or null
              for (var nextKey in nextSource) {
                // Avoid bugs when hasOwnProperty is shadowed
                if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                  to[nextKey] = nextSource[nextKey];
                }
              }
            }
          }

          return to;
        },
        writable: true,
        configurable: true
      });
    }

    if (!Array.prototype.includes) {
      Object.defineProperty(Array.prototype, 'includes', {
        value: function value(valueToFind, fromIndex) {
          if (this == null) {
            throw new TypeError('"this" is null or not defined');
          } // 1. Let O be ? ToObject(this value).


          var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")).

          var len = o.length >>> 0; // 3. If len is 0, return false.

          if (len === 0) {
            return false;
          } // 4. Let n be ? ToInteger(fromIndex).
          //    (If fromIndex is undefined, this step produces the value 0.)


          var n = fromIndex | 0; // 5. If n ≥ 0, then
          //  a. Let k be n.
          // 6. Else n < 0,
          //  a. Let k be len + n.
          //  b. If k < 0, let k be 0.

          var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

          function sameValueZero(x, y) {
            return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
          } // 7. Repeat, while k < len


          while (k < len) {
            // a. Let elementK be the result of ? Get(O, ! ToString(k)).
            // b. If SameValueZero(valueToFind, elementK) is true, return true.
            if (sameValueZero(o[k], valueToFind)) {
              return true;
            } // c. Increase k by 1. 


            k++;
          } // 8. Return false


          return false;
        }
      });
    }

    if (!Object.keys) {
      Object.keys = function () {
        var hasOwnProperty = Object.prototype.hasOwnProperty,
            hasDontEnumBug = !{
          toString: null
        }.propertyIsEnumerable('toString'),
            dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'],
            dontEnumsLength = dontEnums.length;
        return function (obj) {
          if (_typeof(obj) !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
          var result = [];

          for (var prop in obj) {
            if (hasOwnProperty.call(obj, prop)) result.push(prop);
          }

          if (hasDontEnumBug) {
            for (var i = 0; i < dontEnumsLength; i++) {
              if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
            }
          }

          return result;
        };
      }();
    }

    ;

    if (!Object.values) {
      Object.values = function (obj) {
        if (obj !== Object(obj)) throw new TypeError('Object.values called on a non-object');
        var val = [],
            key;

        for (key in obj) {
          if (Object.prototype.hasOwnProperty.call(obj, key)) {
            val.push(obj[key]);
          }
        }

        return val;
      };
    }
  };

  var wx = function () {
    var wx = {};
    wx.open_loading = false;

    wx.loading = function (loading_text) {
      if (!wx.open_loading) {
        return {
          hide: function hide(callback) {
            callback && callback();
          }
        };
      }

      return weui.loading(loading_text || "加载中");
    };

    var loader = function loader(callback) {
      var loading = wx.loading("加载中");

      util.require(['wx'], function (wxsdk) {
        loading.hide(function () {
          callback && callback(wxsdk);
        });
      }, function (err) {
        console.error("微信功能加载错误，可能是未加载jssdk(jweixin)导致");
      });
    };

    wx.init = function (access, options, callback) {
      options = Object.assign({
        apiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'translateVoice', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'onVoicePlayEnd', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getLocalImgData', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView']
      }, options);
      loader(function (wxsdk) {
        wxsdk.hideAllNonBaseMenuItem();
        wxsdk.showMenuItems({
          menuList: ['menuItem:copyUrl']
        });
        wxsdk.config({
          debug: false,
          appId: access.appId,
          timestamp: access.timestamp,
          nonceStr: access.nonceStr,
          signature: access.signature,
          jsApiList: options.apiList
        });
        callback && callback(wxsdk);
      });
    };

    wx.uploadImage = function () {
      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var callback = arguments.length > 1 ? arguments[1] : undefined;
      options = Object.assign({
        count: 9,
        sizeType: ['compressed'],
        // 可以指定是原图original还是压缩图compressed，默认二者都有
        sourceType: ['album'] // 可以指定来源是相册album还是相机camera，默认二者都有

      }, options);

      var local2base64 = function local2base64(localIds, callback) {
        var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
        var files = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
        var localId = localIds[index];

        if (util.isEmpty(localId)) {
          callback && callback(files);
          return;
        }

        loader(function (wxsdk) {
          wxsdk.getLocalImgData({
            localId: localId,
            success: function success(res) {
              var imagebase64 = res.localData;
              var imageblob = util.base642Blob(imagebase64);
              var file = util.blob2File(imageblob, "wx_" + util.getCalendarDate().timestamp + index + "." + util.defaults(util.defaults(imageblob.type, "").split('/')[1], "jpg"), {
                type: imageblob.type
              });
              files.push(file);
              local2base64(localIds, callback, index + 1, files);
            }
          });
        });
      };

      options.success = function (res) {
        local2base64(res.localIds, function (files) {
          callback && callback(files);
        });
      };

      loader(function (wxsdk) {
        wxsdk.chooseImage(options);
      });
    };

    return wx;
  }();

  var util = function () {
    var util = {};
    var toString = Object.prototype.toString;
    var slice = Array.prototype.slice;
    /** 
     * 获取当前设备类型
     */

    util.device = function () {
      var userAgentInfo = navigator.userAgent;
      var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
      var flag = true;

      for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
          flag = false;
          break;
        }
      } // 如果未找到以上标识，视为pc端


      if (flag) {
        return "pc";
      } // 安卓


      if (userAgentInfo.indexOf('Android') > -1 || userAgentInfo.indexOf('Linux') > -1) {
        return "android";
      } // iOS


      if (!!userAgentInfo.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        return "ios";
      }

      return "unknown";
    };

    util.isWechatDevice = function () {
      var ua = window.navigator.userAgent.toLowerCase();
      return !!(ua.match(/MicroMessenger/i) == 'micromessenger');
    };
    /**
     * 下载文件
     * url：下载文件的远程地址
     */


    util.download = function (url) {
      var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";

      if (window.document) {
        var a = document.createElement("a");
        a.href = url; // 支持download时使用download，不支持时使用a标签跳转

        if ("download" in a) {
          a.setAttribute("download", name);
        } else {
          a.setAttribute("target", "_blank");
        }

        a.click();
      } else {
        window.open(url);
      }
    };
    /**
     * 判断传入的变量是否是一个dom对象
     */


    util.isDom = function (dom) {
      return (typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement)) === 'object' ? dom instanceof HTMLElement : dom && _typeof(dom) === 'object' && dom.nodeType === 1 && typeof dom.nodeName === 'string';
    };
    /**
     * 判断数据的具体类型
     */


    util.type = function (mixin) {
      if (mixin == null) {
        return mixin + "";
      }

      var class2type = {
        '[object Boolean]': 'boolean',
        '[object Number]': 'number',
        '[object String]': 'string',
        '[object Function]': 'function',
        '[object Array]': 'array',
        '[object Date]': 'date',
        '[object RegExp]': 'regexp',
        '[object Object]': 'object',
        '[object Error]': 'error',
        '[object Symbol]': 'symbol',
        '[object File]': 'file'
      };

      var mixin_type = _typeof(mixin);

      if (mixin_type === 'undefined') {
        return 'undefined';
      }

      if (mixin_type === 'object' || mixin_type === "function") {
        var _type = class2type[toString.call(mixin)];

        if (!_type) {
          return util.isDom(mixin) ? "dom" : "object";
        } else {
          return _type;
        }
      }

      return mixin_type;
    };
    /**
     * 是否为空值，不包括0
     */


    util.isEmpty = function (mixin) {
      var _type = util.type(mixin);

      if (_type == "number" && isNaN(mixin)) {
        return true;
      }

      if (["null", "undefined"].includes(_type)) {
        return true;
      }

      if (_type == "boolean" && mixin == false) {
        return true;
      }

      if (_type == "array" && mixin.length == 0) {
        return true;
      }

      if (_type == "file") {
        return false;
      }

      if (_type == "object" && Object.keys(mixin).length == 0) {
        return true;
      }

      return mixin === "";
    };
    /** 
     * 符合 type() 函数的验证，如果验证不成功适用默认值
     */


    util.defaults = function (mixin) {
      var defaults = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
      var compareFunction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : util.isEmpty;
      return compareFunction(mixin) ? defaults : mixin;
    };
    /** 
     * 获取get参数
     */


    util.getQuery = function () {
      var search = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : location.search;
      var query = {};

      if (search.indexOf("?") != -1) {
        search = search.split("?")[1];
      }

      search.split("&").map(function (item) {
        var srt = item.split("=");

        if (srt[0] != "") {
          query[srt[0]] = srt[1];
        }
      });
      return query;
    };
    /**
     * 将query转为hash字符串
     */


    util.query2Hash = function (query) {
      var query_trim = [];

      for (var i in query) {
        query_trim.push(i + '=' + query[i]);
      }

      return query_trim.join('&');
    };
    /**
     * 数字前补0变为字符串数字
     */


    util.fullZeroNumber = function (number) {
      var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;

      var __number = number + "";

      if (isNaN(__number)) {
        return number;
      }

      while (__number.length < size) {
        __number = "0" + __number;
      }

      return __number;
    };
    /**
     * 获取设置时间的小时分钟秒
     */


    util.getCalendarDate = function () {
      var ND = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();

      if (ND.hasOwnProperty("__calendarDate__")) {
        return ND;
      }

      if (util.type(ND) == "string") {
        ND = ND.trim().replace(/-/g, "/");
      }

      if (util.isEmpty(ND)) {
        ND = new Date();
      } else {
        ND = new Date(ND);
      }

      var NW = {
        // 时间对象
        ND: ND,
        // 年
        year: ND.getFullYear() + "",
        // 月
        month: util.fullZeroNumber(ND.getMonth() + 1),
        // 日
        day: util.fullZeroNumber(ND.getDate()),
        // 小时
        hour: util.fullZeroNumber(ND.getHours()),
        // 分钟
        minute: util.fullZeroNumber(ND.getMinutes()),
        // 秒
        second: util.fullZeroNumber(ND.getSeconds()),
        // 周
        week: ND.getDay() == 0 ? "7" : ND.getDay() + "",
        // 当前时间毫秒时间戳
        timestamp: ND.getTime() + ""
      };
      Object.defineProperty(NW, "__calendarDate__", {
        enumerable: false,
        value: ND,
        writable: false
      });
      NW.secondTimestamp = NW.timestamp.slice(0, -3); // 格式化显示

      NW.format = function () {
        var format = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "Y-m-d";
        var formatExec = /[YmdHis]/g;
        var formatMap = {
          "Y": NW.year,
          "m": NW.month,
          "d": NW.day,
          "H": NW.hour,
          "i": NW.minute,
          "s": NW.second,
          "w": NW.week
        };
        var p = null;
        var text = format;

        while (p = formatExec.exec(format)) {
          text = text.replace(p[0], formatMap[p[0]]);
        }

        return text;
      };

      function overall(ND) {
        if (ND.getTime() == NW.timestamp) {
          return NW;
        }

        return util.getCalendarDate(ND);
      } // 依据当天的统计信息


      NW.overall = {};
      var overallMap = {
        day: [NW.year, +NW.month - 1, NW.day],
        firstOfYear: [NW.year, 0, 1],
        endOfYear: [+NW.year + 1, 0, 0],
        firstOfMonth: [NW.year, +NW.month - 1, 1],
        endOfMonth: [NW.year, NW.month, 0],
        firstOfWeek: [NW.year, +NW.month - 1, NW.day - NW.week + 1],
        endOfWeek: [NW.year, +NW.month - 1, NW.day - NW.week + 7]
      };

      var _loop = function _loop(_name) {
        NW.overall[_name] = function () {
          return overall(_construct(Date, _toConsumableArray(overallMap[_name])));
        };
      };

      for (var _name in overallMap) {
        _loop(_name);
      } // 计算范围距离


      NW.step = {
        day: function day() {
          return Math.floor(NW.step.secondOfYear() / 86400) + 1 + "";
        },
        week: function week() {
          return Math.floor((NW.step.day() - NW.week) / 7) + 1 + "";
        },
        secondOfYear: function secondOfYear() {
          return NW.overall.day().secondTimestamp - NW.overall.firstOfYear().secondTimestamp + "";
        }
      };
      return NW;
    };
    /**
     * 类数组转为真正数组
     */


    util.like2Array = function (likeArray) {
      return slice.call(likeArray);
    };
    /**
     * 获取文件的md5值
     * shim: SparkMD5
     */


    util.getFileMd5 = function (file, callback) {
      require(["SparkMD5"], function (SparkMD5) {
        //声明必要的变量
        var fileReader = new FileReader(); //文件分割方法（注意兼容性）

        var blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice,
            //文件每块分割2M，计算分割详情
        chunkSize = 2097152,
            chunks = Math.ceil(file.size / chunkSize),
            currentChunk = 0,
            //创建md5对象（基于SparkMD5）
        spark = new SparkMD5();
        var filename = file.name; //每块文件读取完毕之后的处理

        fileReader.onload = function (e) {
          // trace("读取文件", currentChunk + 1, "/", chunks);
          //每块交由sparkMD5进行计算
          spark.appendBinary(e.target.result);
          currentChunk++; //如果文件处理完成计算MD5，如果还有分片继续处理

          if (currentChunk < chunks) {
            loadNext();
          } else {
            // 前台显示Hash
            callback && callback({
              name: filename,
              size: file.size + "",
              KB: (file.size / 1024).toFixed(2),
              MB: (file.size / 1024 / 1024).toFixed(2),
              GB: (file.size / 1024 / 1024 / 1024).toFixed(2),
              md5: spark.end()
            });
          }
        }; //处理单片文件的上传


        function loadNext() {
          var start = currentChunk * chunkSize,
              end = start + chunkSize >= file.size ? file.size : start + chunkSize;
          fileReader.readAsBinaryString(blobSlice.call(file, start, end));
        }

        loadNext();
      });
    };
    /** 
     * arraybuffer内容转为字符串
     */


    util.buffer2String = function (buffer) {
      var encodedString = String.fromCodePoint.apply(null, new Uint8Array(buffer)); // 没有这一步中文会乱码

      var decodedString = decodeURIComponent(escape(encodedString));
      return decodedString;
    };
    /** 
     * base64转blob
     */


    util.base642Blob = function (base64Data) {
      var defaultmime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "data:image/jpg;base64";

      if (base64Data.indexOf("data:") != 0) {
        base64Data = defaultmime + "," + base64Data;
      }

      var byteString;
      if (base64Data.split(',')[0].indexOf('base64') >= 0) byteString = atob(base64Data.split(',')[1]);else byteString = unescape(base64Data.split(',')[1]);
      var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
      var ia = new Uint8Array(byteString.length);

      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }

      return new Blob([ia], {
        type: mimeString
      });
    };
    /** 
     * blob转file
     */


    util.blob2File = function (blob, name) {
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      // blob.lastModifiedDate = new Date();
      // blob.name = name;
      // return blob;
      options = Object.assign({
        type: "image/jpg"
      }, options);
      return new File([blob], name, options);
    };
    /** 
     * 创建一个类数组结构，并且返回可塑造方法
     */


    util.likeArray = function () {
      var struct = {
        length: 0
      };
      return {
        /** 
         * 追加类数组内容。可以追加一个非类数组的key存入，只不过最后将不能生成为真正的数组
         */
        add: function add(value) {
          var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : struct.length;

          if (key == "length") {
            trace("Error:util", "util.likeArray.add 不支持追加 \"length\"字段");
            return key;
          }

          struct[key] = value;
          struct.length += 1;
          return key;
        },
        remove: function remove(key) {
          if (util.isEmpty(key) || key == "length" || !struct.hasOwnProperty(key)) {
            return false;
          }

          delete struct[key];
          struct.length -= 1;
          return true;
        },

        /** 
         * 是类数组就返回数组，不是类数组返回对象（没有length属性）
         */
        get: function get() {
          if (Object.keys(slice.call(struct)).length == struct.length) {
            return slice.call(struct);
          } else {
            var res = Object.assign({}, struct);
            delete res.length;
            return res;
          }
        },
        __name__: "likeArray"
      };
    };
    /**
     * 获取某元素以浏览器左上角为原点的坐标
     */


    util.offset = function (dom) {
      var top = dom.offsetTop;
      var left = dom.offsetLeft;
      var width = dom.offsetWidth;
      var height = dom.offsetHeight;

      while (dom = dom.offsetParent) {
        top += dom.offsetTop;
        left += dom.offsetLeft;
      }

      return {
        top: top,
        left: left,
        width: width,
        height: height
      };
    };
    /** 
     * textarea不回弹
     */


    util.iosTextBlurScroll = function (input) {
      if (!input) {
        return false;
      }

      var trueHeight = document.body.scrollHeight; //解决ios唤起键盘后留白

      var backPageSize = function backPageSize() {
        setTimeout(function () {
          window.scroll(0, trueHeight - 10);
          window.innerHeight = window.outerHeight = trueHeight;
        }, 200);
      };

      input.onblur = backPageSize; // onblur是核心方法
    };
    /** 
     * 获取 xx:xx 转为当天秒数
     */


    util.getHoursSecond = function (hoursFormat) {
      var _mm$;

      if (!/^\d\d\:\d\d(\:\d\d)?$/.test(hoursFormat)) {
        return false;
      }

      var mm = hoursFormat.split(":");
      console.log(mm);
      return mm[0] * 3600 + mm[1] * 60 + +((_mm$ = mm[2]) !== null && _mm$ !== void 0 ? _mm$ : 0);
    };
    /** 
     * 依赖jQuery
     * 通过jQuery的serializeArray方法获取form表单中的所有字段值
     * 如果包含数组类内容，暂只支持一维数组
     * 
     * @param form 页面form的dom，或者form的jquery-dom
     */


    util.getFields = function (form) {
      var filter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (val) {
        return true;
      };
      var fields = {};
      $(form).serializeArray().map(function (d) {
        var value = d.value.trim();

        if (/[\[\]\.]/.test(d.name)) {
          var reg = /^([^.\[\]]+)+(\[(.*?)\]|\.)*?$/g;
          var exec = null;

          while (exec = reg.exec(d.name)) {
            if (!fields.hasOwnProperty(exec[1])) {
              fields[exec[1]] = util.likeArray();
            }

            if (util.isEmpty(exec[3])) {
              if (filter(value, exec[1])) {
                fields[exec[1]].add(value);
              }
            } else {
              if (filter(value, exec[1])) {
                fields[exec[1]].add(value, exec[3]);
              }
            }
          }
        } else {
          if (filter(value, d.key)) {
            fields[d.name] = value;
          }
        }
      }); // 将类数组转为数组

      for (var i in fields) {
        if (fields[i].__name__ == "likeArray") {
          fields[i] = fields[i].get();
        }
      }

      return fields;
    };
    /** 
     * 修改Object.assign，不向前追加前者没有的属性
     */


    util.objectInset = function () {
      var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      for (var i in target) {
        if (source.hasOwnProperty(i)) {
          target[i] = source[i];
        }
      }

      return target;
    };
    /** 
     * 正则匹配
     */


    util.is = function (pattern) {
      var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

      if (util.type(pattern) == "regexp") {
        return pattern.test(value);
      }

      var rules = function rules(pattern, value) {
        switch (pattern) {
          case "empty":
            pattern = '^$';
            break;

          case "url":
            pattern = "^(((http|https)):\\/\\/)[\\w-]+(\\.[\\w-]+)+([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?$";
            break;

          case "urlsimple":
            pattern = "^(((http|https)):\\/\\/)?[\\w-]+(\\.[\\w-]+)+([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?$";
            break;

          case "host":
            pattern = "^[\\w-]+(\\.[\\w-]+)+$";
            break;

          case "nosymbol":
            pattern = "^[^\\<\\>\\{\\}]*$";
            break;

          default:
            throw "util.is 使用了不支持的验证规则";
        }

        pattern = new RegExp(pattern);
        return pattern.test(value);
      };

      if (pattern.indexOf("|") != -1) {
        var pattern_ors = pattern.split("|");
        var or_valid = false;

        for (var i = 0; i < pattern_ors.length; i++) {
          var pattern_or = pattern_ors[i];

          if (pattern_or.indexOf("&") != -1) {
            var pattern_ands = pattern_or.split("&");
            var and_valid = true;

            for (var j = 0; j < pattern_ands.length; j++) {
              var pattern_and = pattern_ands[j];

              if (!rules(pattern_and, value)) {
                and_valid = false;
              }
            }

            if (and_valid) {
              or_valid = true;
            }
          } else {
            if (rules(pattern_or, value)) {
              or_valid = true;
            }
          }
        }

        return or_valid;
      } else {
        return rules(pattern, value);
      }
    };

    util.jsonparse = function (data) {
      var defaults = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      var parse;

      try {
        parse = JSON.parse(data);
      } catch (error) {
        parse = defaults;
      }

      if (key !== false) {
        return util.defaults(parse[key], "");
      }

      return parse;
    };

    util.lang = function (key, language) {
      var err = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};
      var langs = lang[language];

      if (!langs) {
        err && err("[Lang]: \u8BED\u8A00\u5305 ".concat(language, " \u4E0D\u53EF\u7528\uFF0C\u53EF\u80FD\u672A\u8BBE\u7F6E\u8BED\u8A00\u5305"));
        return "";
      }

      if (!langs.hasOwnProperty(key)) {
        err && err("[Lang]: 未找到的语言包内容，加载关键字：" + key);
        return "";
      }

      var value = langs[key];

      if (typeof value != "string") {
        err && err("[Lang]: \u8BED\u8A00\u5305\u5173\u952E\u5B57 ".concat(key, " \u52A0\u8F7D\u9519\u8BEF\uFF1A\u53EF\u80FD\u8BBE\u7F6E\u4E86\u4E00\u4E2A\u4E0D\u53EF\u8BFB\u53D6\u6216\u975E\u5B57\u7B26\u4E32\u7C7B\u578B\u7684\u8BED\u8A00"));
        return "";
      }

      return value;
    };

    var astralRange = /\ud83c[\udffb-\udfff](?=\ud83c[\udffb-\udfff])|(?:[^\ud800-\udfff][\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0]?|[\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0]|\ud83c[\udffb-\udfff])?)*/g;

    var EmojiCharString = /*#__PURE__*/function () {
      function EmojiCharString(string) {
        _classCallCheck(this, EmojiCharString);

        if (typeof string !== 'string') {
          throw new Error('Input must be a string');
        }

        this._string = string;
        this._match = string.match(astralRange) || [];
      }

      _createClass(EmojiCharString, [{
        key: "toString",
        value: function toString() {
          return this._string;
        }
        /**
         * Reverse the string in place
         * @return {[String]} [The reversed string]
         */

      }, {
        key: "reverse",
        value: function reverse() {
          return this._match.reverse().join('');
        }
        /**
         * The substring() method returns a subset of a string between begin index and end index
         * @param  {Number} begin [begin index]
         * @param  {Number} end   [end index]
         * @return {[String]}     [A new string containing the extracted section of the given string.]
         */

      }, {
        key: "substring",
        value: function substring() {
          var begin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
          var end = arguments.length > 1 ? arguments[1] : undefined;
          var strLen = this.length;
          var indexStart = (parseInt(begin, 10) || 0) < 0 ? 0 : parseInt(begin, 10) || 0;
          var indexEnd;

          if (typeof end === 'undefined') {
            indexEnd = strLen;
          } else {
            indexEnd = (parseInt(end, 10) || 0) < 0 ? 0 : parseInt(end, 10) || 0;
          }

          if (indexStart > strLen) {
            indexStart = strLen;
          }

          if (indexEnd > strLen) {
            indexEnd = strLen;
          }

          if (indexStart > indexEnd) {
            var _ref = [indexEnd, indexStart];
            indexStart = _ref[0];
            indexEnd = _ref[1];
          }

          return this._match.slice(indexStart, indexEnd).join('');
        }
        /**
         * The substr() method return the characters in a string beginning at the specified location through the specified number of characters.
         * @param  {Number} begin [Location at which to begin extracting characters]
         * @param  {Number} len   [The number of characters to extract]
         * @return {[String]}     [A new string containing the extracted section of the given string]
         */

      }, {
        key: "substr",
        value: function substr() {
          var begin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
          var len = arguments.length > 1 ? arguments[1] : undefined;
          var strLen = this.length;
          var indexStart = parseInt(begin, 10) || 0;
          var indexEnd;

          if (indexStart >= strLen || len <= 0) {
            return '';
          } else if (indexStart < 0) {
            indexStart = Math.max(0, indexStart + strLen);
          }

          if (typeof len === 'undefined') {
            indexEnd = strLen;
          } else {
            indexEnd = indexStart + (parseInt(len, 10) || 0);
          }

          return this._match.slice(indexStart, indexEnd).join('');
        }
      }, {
        key: "length",
        get: function get() {
          return this._match.length;
        }
      }]);

      return EmojiCharString;
    }();

    util.emojiString = function (string) {
      return new EmojiCharString(string);
    };

    util.define = function () {};

    util.require = function (deps, callback, errback) {
      if (typeof require === 'function') {
        require(deps, callback);
      } else {
        if (util.type(deps) != "array") {
          errback && errback("deps参数错误：" + deps);
          return false;
        }

        var depsCom = [];

        for (var i = 0; i < deps.length; i++) {
          if (!window.hasOwnProperty(deps[i])) {
            errback && errback(deps[i] + "未加载成功");
            return false;
          }

          depsCom.push(window[deps[i]]);
        }

        callback && callback.apply(undefined, depsCom);
      }
    }; //= block:main


    return util;
  }();

  var cache = function () {
    var cache = {};
    var appStorage = {};
    var timeKeySuffix = "~overdueTime";

    cache.get = function (key) {
      var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : APP_STORAGE;
      var time = util.getCalendarDate(new Date());
      var timeKey = key + timeKeySuffix; // 过期时间

      var storageTime; // 数据

      var storageValue; // 获取数据及过期时间

      switch (type) {
        case APP_STORAGE:
          var ase = appStorage[key];

          if (util.isEmpty(ase)) {
            ase = {
              storageTime: null,
              storageValue: null
            };
          }

          storageTime = ase.storageTime;
          storageValue = ase.storageValue;
          break;

        case SESSION_STORAGE:
          storageTime = sessionStorage.getItem(timeKey);
          storageValue = sessionStorage.getItem(key);
          break;

        case LOCAL_STORAGE:
          storageTime = localStorage.getItem(timeKey);
          storageValue = localStorage.getItem(key);
      } // 未获取到时


      if (storageValue === null || storageTime === null) {
        return null;
      } // json字符串转为object


      try {
        storageValue = JSON.parse(storageValue);
      } catch (e) {} // 如果有过期时间，检测是否已过期


      if (~~storageTime > 0) {
        if (storageTime < time.timestamp) {
          sessionStorage.removeItem(timeKey);
          sessionStorage.removeItem(key);
          storageValue = null;
        }
      }

      return storageValue;
    };
    /** 
     * 缓存数据
     */


    cache.set = function (key, value) {
      var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : APP_STORAGE;
      var overdueSecond = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
      var time = util.getCalendarDate(new Date());
      var timeKey = key + timeKeySuffix; // 过期时间，0表示不设置过期

      var overdueTime = 0;

      if (overdueSecond !== null) {
        overdueTime = +time.timestamp + ~~overdueSecond * 1000;
      } // 获取数据及过期时间


      switch (type) {
        case APP_STORAGE:
          if (value === null) {
            delete appStorage[key];
            return;
          }

          appStorage[key] = {
            storageTime: overdueTime,
            storageValue: value
          };
          break;

        case SESSION_STORAGE:
          if (value === null) {
            sessionStorage.removeItem(timeKey);
            sessionStorage.removeItem(key);
            return;
          }

          sessionStorage.setItem(timeKey, overdueTime);

          try {
            sessionStorage.setItem(key, JSON.stringify(value));
          } catch (e) {
            sessionStorage.setItem(key, value);
          }

          break;

        case LOCAL_STORAGE:
          if (value === null) {
            localStorage.removeItem(timeKey);
            localStorage.removeItem(key);
            return;
          }

          localStorage.setItem(timeKey, overdueTime);

          try {
            localStorage.setItem(key, JSON.stringify(value));
          } catch (e) {
            localStorage.setItem(key, value);
          }

      }
    };

    return cache;
  }();

  var config = function () {
    function getConfig() {
      var _config = {
        // 微信功能注册接口地址
        JSSDK_URL: "/shijiwxy/wechat/portal/getWxJsConfig.json",
        // 请求路径
        API_HOST: "",
        // 请求header参数
        API_HEADER: {}
      }; // 版本信息

      Object.defineProperties(_config, {
        DEBUG: {
          value: true,
          writable: false
        },
        VERSION: {
          value: VERSION,
          writable: false
        }
      });
      return _config;
    }

    var _config = getConfig();

    _config.reset = function (base) {
      Object.assign(_config, base);
    };

    return _config;
  }();

  var api = function () {
    var api = {};
    api.debug = false;
    var _xhrFields = {}; // 处理请求前xhr，每次请求完毕后还原为 {}

    Object.defineProperty(api, "xhrFields", {
      enumerable: false,
      get: function get() {
        return _xhrFields;
      },
      set: function set() {
        _xhrFields = {};
        return _xhrFields;
      }
    });
    /** 
     * 获取请求参数
     */

    function requestParams() {
      var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var method = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : AJAX_PARAMS_MATHOD_JSON;
      var takeCommonQuery = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
      var query = Object.assign({}, params);

      if (takeCommonQuery) {
        Object.assign(query, config.API_HEADER);
      } // undefined项转为""


      for (var i in query) {
        if (query[i] == undefined) {
          query[i] = "";
        }
      }

      switch (method) {
        case AJAX_PARAMS_MATHOD_JSON:
          return query;

        case AJAX_PARAMS_MATHOD_FORMDATA:
          var fd = new FormData();

          for (var _i in query) {
            fd.append(_i, query[_i]);
          }

          return fd;

        case AJAX_PARAMS_MATHOD_STRINGIFY:
          var s = [];

          for (var _i2 in query) {
            s.push(_i2 + "=" + query[_i2]);
          }

          return s.join("&");
      }
    }

    function post(url, data) {
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      return $.ajax({
        url: url,
        type: 'POST',
        data: requestParams(data, AJAX_PARAMS_MATHOD_FORMDATA, true),
        cache: false,
        processData: false,
        contentType: false,
        headers: options.headers,
        xhrFields: Object.assign(api.xhrFields, options.xhrFields)
      });
    }

    function get(url, data) {
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      return $.ajax({
        url: url,
        type: 'GET',
        data: requestParams(data, AJAX_PARAMS_MATHOD_STRINGIFY, true),
        cache: false,
        processData: false,
        contentType: false,
        headers: options.headers,
        xhrFields: Object.assign(api.xhrFields, options.xhrFields)
      });
    }

    function jsonp(url, data) {
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      return $.ajax({
        url: url,
        type: 'JSONP',
        data: Object.assign(requestParams(data, AJAX_PARAMS_MATHOD_STRINGIFY), options.headers),
        cache: false,
        processData: false,
        contentType: false,
        xhrFields: Object.assign(api.xhrFields, options.xhrFields)
      });
    }
    /** 
     * 执行请求
     * 依赖 $.ajax
     */


    api.request = function (url) {
      var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

      if (util.isEmpty(url)) {
        throw "未指定请求地址";
      }

      if (url.indexOf("http") !== 0) {
        url = config.API_HOST + "" + url;
      }

      options = Object.assign({
        method: "POST",
        loading: true,
        headers: true,
        done: function done() {},
        fail: function fail() {}
      }, options);

      if (["boolean", "object"].includes(util.type(options.headers))) {
        if (options.headers === false) {
          options.headers = {};
        } else if (options.headers === true) {
          options.headers = requestParams();
        } else {
          options.headers = Object.assign(requestParams(), options.headers);
        }
      }

      if (api.debug) {
        console.log(options.method + " " + url.replace("https://", ""), data);
      }

      var loading = {
        hide: function hide(callback) {
          callback && callback();
        }
      };

      if (options.loading) {// loading = component.loading();
      }

      var request;

      if (options.method == AJAX_REQUEST_GET) {
        request = get(url, data, options);
      } else if (options.method == AJAX_REQUEST_JSONP) {
        request = jsonp(url, data, options);
      } else {
        request = post(url, data, options);
      }

      return request.done(function (result) {
        loading.hide(function () {
          // 如果请求成功，但接口返回失败，提示错误
          if (result.success !== true) {
            options.fail && options.fail({
              code: result.code,
              message: result.message,
              data: result.data,
              response: request
            });
            return;
          }

          options.done && options.done(result, true);
        });
      }).fail(function (e) {
        loading.hide(function () {
          // 如果是手动中断，不弹出提示
          if (e.statusText == 'abort') {
            return false;
          }

          options.fail && options.fail({
            code: -1,
            message: '服务器繁忙，请重试',
            data: {},
            response: e
          });
        });
      });
    };
    /** 
     * 获取esb图片
     */


    api.esbImageUrl = function (url) {
      var imgName = url.split(".")[0];
      return config.API_HOST + "/esb/res/pic/" + Math.floor(+imgName / 10000) + "/" + Math.floor(+imgName / 100) + "/" + url;
    };
    /** 
     * 注册jssdk
     * 需要引入wx模块
     */


    api.jssdkRegister = function () {
      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
        org_id: ""
      };
      var callback = arguments.length > 1 ? arguments[1] : undefined;

      var _fail = arguments.length > 2 ? arguments[2] : undefined;

      api.request(config.API_HOST + config.JSSDK_URL, Object.assign({
        url: window.location.href
      }, options), {
        done: function done(result) {
          var access = result.data;
          wx.init(access, {}, function () {
            callback && callback();
          });
        },
        fail: function fail(e) {
          _fail && _fail(e);
        }
      });
    }; // = block:main


    return api;
  }();

  var component = function () {
    var render = function () {
      var render = {};

      render.getContainer = function () {
        var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
        var DOM = render.create('<div id="' + id + '"></div>');
        return {
          el: DOM,
          // 支持格式： 
          // append("")  append(dom) append(Component) append([dom1, dom2, Component])
          // append(Component, dom)
          // 这种不行：
          // append("", [dom]) append([Template], "")
          append: function append(template) {
            var templates = Array.prototype.slice.call(arguments); // 如果第一个参数传了数组，后面的参数无效

            if (util.type(template) == "array") {
              templates = template;
            }

            templates.map(function (template) {
              var type = util.type(template);

              if (util.isEmpty(template)) {
                return false;
              }

              if (type == "string") {
                template = template.trim();

                if (template.length == 0) {
                  return false;
                }

                template = render.create(template);
                type = "dom";
              }

              if (type == "dom") {
                return template;
              }

              if (util.type(template.el) == "dom") {
                return template.el;
              }

              return false;
            }).filter(function (dom) {
              return dom !== false;
            }).map(function (dom) {
              DOM.appendChild(dom);
            });
            return this;
          },
          render: function render(selector) {
            if (typeof selector == 'undefined') {
              var original = document.querySelector('#' + id);
              original.parentNode.replaceChild(DOM, original);
            } else {
              var parent = document.querySelector(selector);
              parent.append(DOM);
            }

            setTimeout(function () {
              DOM.className = (DOM.className + " on").trim();
            }, 100);
          }
        };
      };
      /**
       * 通过字符串模板创建DOM
       * @param {String} string 字符串模板，模板必须包含一个最外层标签
       */


      render.create = function (string) {
        var Element = document.createElement('div');
        string = string.trim();
        var wrapMap = {
          thead: [1, "<table>", "</table>"],
          tbody: [1, "<table>", "</table>"],
          col: [2, "<table><colgroup>", "</colgroup></table>"],
          tr: [2, "<table><tbody>", "</tbody></table>"],
          td: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
          th: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
          _default: [0, "", ""]
        };
        var tag = (/<([a-z][^\/\0>\x20\t\r\n\f]*)/i.exec(string) || ["", ""])[1].toLowerCase();
        var wrap = wrapMap[tag] || wrapMap._default;
        Element.innerHTML = wrap[1] + string + wrap[2];
        var j = wrap[0];

        while (j--) {
          Element = Element.lastChild;
        }

        return Element.firstChild;
      };

      render.compile = function (DOM, template) {
        var event = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};
        var Element = this.create(template);
        event && event(Element);

        if (typeof DOM == 'string') {
          DOM = document.querySelector(DOM);
        }

        DOM.appendChild(Element);
      };

      return render;
    }();

    var component = {};
    /** 
     * 创建组件容器
     */

    component.getContainer = function () {
      var container = render.getContainer("app");
      return container;
    };
    /**
     * 获取定制数组重构方法
     */


    function getArrayArgumentations(callback) {
      var aryMethods = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'];
      var arrayArgumentations = [];
      aryMethods.forEach(function (method) {
        var original = Array.prototype[method];

        arrayArgumentations[method] = function () {
          var result = original.apply(this, arguments);
          callback && callback(method);
          return result;
        };
      }); // 清空数组只保留项数

      arrayArgumentations.clear = function () {
        var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
        this.length = length;
        callback && callback('clear');
        return this;
      };

      return arrayArgumentations;
    }

    ;
    /** 
     * 热更新
     * 未扩展数组中是对象，对象里面的监听情况
     */

    function hotData() {
      var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var callback = arguments.length > 1 ? arguments[1] : undefined;
      var deepPrefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";

      var _type = util.type(data);

      if (_type == "array") {
        data.__proto__ = getArrayArgumentations(function (method) {
          callback && callback(deepPrefix + name, [data]);
        });

        for (var i = 0; i < data.length; i++) {
          data[i] = hotData(data[i], callback, deepPrefix + i + ".");
        }

        return data;
      } else if (_type == "object") {
        var __DATA__ = {};

        var _loop2 = function _loop2(_name2) {
          var data_type = util.type(data[_name2]);

          if (data_type == "array") {
            __DATA__[_name2] = hotData(data[_name2], callback, deepPrefix + _name2 + ".");
          } else if (data_type == "object") {
            __DATA__[_name2] = hotData(data[_name2], callback, deepPrefix + _name2 + ".");
          } else {
            Object.defineProperty(__DATA__, _name2, {
              enumerable: true,
              get: function get() {
                return data[_name2];
              },
              set: function set(val) {
                data[_name2] = val;
                callback && callback(deepPrefix + _name2, [val]);
                return data[_name2];
              }
            });
          }
        };

        for (var _name2 in data) {
          _loop2(_name2);
        }

        return __DATA__;
      }

      return data;
    }
    /** 
     * 热更新
     */


    component.hotData = hotData;
    /** 
     * 字符串html、DOM结构化返回DOM；
     * ComponentDOM原样返回
     */

    component.structure = function (template) {
      if (util.type(template) == "object" && template.__OBJTYPE__ == OBJTYPE) {
        return template;
      }

      if (util.isDom(template)) {
        return template;
      } // 强制转为字符串


      template = String(template); // 处理带数据的字符串模板
      // 匹配如同 {{name}} 的字符串模板

      var reg = /\{\{(\w+)\}\}/g;
      var exec = null; // 依次获取匹配内容

      while (exec = reg.exec(template)) {
        // 替换掉真实数据，如果不存在数据，将替换为空字符串
        template = template.replace(new RegExp(exec[0], "g"), util.defaults(data[exec[1]], ""));
      }

      return render.create(template);
    };
    /** 
     * 创建组件模型
     */


    component.create = function (template) {
      var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

      if (util.type(template) == "object" && template.__OBJTYPE__ == OBJTYPE) {
        return template;
      }

      var DOM = component.structure(template);
      var bindSet = {};

      function on(key, callback) {
        if (!bindSet.hasOwnProperty(key)) {
          bindSet[key] = [];
        }

        bindSet[key].push({
          key: key,
          callback: callback
        });
      }

      function off(key) {
        var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

        if (!bindSet.hasOwnProperty(key)) {
          return;
        }

        if (callback === true) {
          delete bindSet[key];
          return;
        }

        for (var i = bindSet[key].length - 1; i >= 0; i--) {
          if (bindSet[key][i].callback == callback) {
            bindSet[key].splice(i, 1);
          }
        }
      }

      function trigger(key, params, defaults) {
        var isTrigger = false;

        if (bindSet.hasOwnProperty(key)) {
          bindSet[key].map(function (set) {
            if (set.callback) {
              isTrigger = true;
              set.callback.apply(set, params);
            }
          });
        }

        if (!isTrigger) {
          defaults && defaults.apply(void 0, [key].concat(_toConsumableArray(params)));
        }
      }

      function onDataChange(name, vals) {
        callback && callback();
      }

      options = Object.assign({
        accessDom: false
      }, options);
      var dataChange = null;

      var __DATA__ = hotData(data, function (name, vals) {
        trigger("data:" + name, vals, dataChange);
      });

      var DOMMAP = {
        el: DOM,
        data: __DATA__,
        on: on,
        off: off,
        trigger: trigger,
        addEventListener: DOM.addEventListener.bind(DOM),
        querySelector: DOM.querySelector.bind(DOM),
        querySelectorAll: DOM.querySelectorAll.bind(DOM),
        appoint: function appoint(selector, data) {
          var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

          try {
            return component.create(DOM.querySelector(selector), data, options);
          } catch (error) {
            if (options.error !== false) {
              console.error("appoint未找到DOM结构：" + selector);
            }

            return null;
          }
        },
        empty: function empty() {
          DOM.innerHTML = "";
          return DOMMAP;
        },
        nfempty: function nfempty() {
          while (DOM.children.length > 1) {
            DOM.removeChild(DOM.lastChild);
          }

          return DOMMAP;
        },
        remove: function remove() {
          if (DOM.parentNode) {
            DOM.parentNode.removeChild(DOM);
          }
        },
        parent: function parent() {
          if (DOM.parentNode) {
            return component.create(DOM.parentNode);
          }
        },
        onDataChange: function onDataChange(callback) {
          dataChange = callback;
        },
        append: function append(template) {
          var templates = Array.prototype.slice.call(arguments); // 如果第一个参数传了数组，后面的参数无效

          if (util.type(template) == "array") {
            templates = template;
          }

          templates.map(function (template) {
            template = component.structure(template);

            if (template.__OBJTYPE__ == OBJTYPE) {
              return template.el;
            } // trace("未识别的模板内容：template不是一个" + OBJTYPE + "对象，已被系统忽略");


            return template;
          }).filter(function (dom) {
            return dom !== false;
          }).map(function (dom) {
            DOM.appendChild(dom);
          });
          return DOMMAP;
        }
      };

      DOMMAP.html = function (DM) {
        DOMMAP.empty().append(component.create(DM));
        return DOMMAP;
      };

      DOMMAP.text = function (text) {
        DOMMAP.empty().el.innerHTML = text;
        return DOMMAP;
      };

      Object.defineProperty(DOMMAP, "__OBJTYPE__", {
        enumerable: false,
        value: OBJTYPE,
        writable: false
      }); // 是否将数据存入到dom上的__DATA__变量中

      if (options.accessDom) {
        DOM.__DATA__ = __DATA__;
      }

      return DOMMAP;
    };

    component.appoint = function (selector, data, options) {
      if (util.isEmpty(selector)) {
        console.error("appoint未找到DOM结构：" + selector);
        return false;
      }

      return component.create(document.querySelector(selector), data, options);
    }; // 上传文件


    component.uploadExcel = function (callback) {
      var DOMMAP = component.create('<input type="file" accept=".xls,.xlsx"/>');
      DOMMAP.addEventListener("change", function (e) {
        var files = e.target.files;

        if (files.length == 0) {
          return;
        }

        callback && callback(files);
      });
      DOMMAP.el.click();
      return DOMMAP;
    };

    component.loading = function (loading_text) {
      var $loading = $("<div class='loading-bg' loading-id='1' style=\"z-index:10200000\"></div><div class='loadingimg' loading-id='2' style=\"z-index:10200000\"><img src='images/loading-2.gif'><div>".concat(loading_text || "数据加载中，请稍后...", "</div></div>"));
      $(".loading-bg").remove();
      $(".loadingimg").remove();
      $(".topbar").after($loading);
      return {
        hide: function hide(callback) {
          var $bg = $(".loading-bg");
          var $img = $(".loadingimg");
          $bg.fadeOut("fast");
          $img.fadeOut("fast");
          callback && callback();
        }
      };
    }; // = block:main


    return component;
  }();

  installer.install("wx", wx);
  installer.install("util", util);
  installer.install("cache", cache);
  installer.append("config", config);
  installer.install("api", api);
  installer.install("component", component);
  installer.append("polyfill", polyfill);
  return installer.get();
});